import nacos
import json
import os
from common.utils.logger import Logger

class NacosClient:
    _instance = None
    _client = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self):
        if not self._client:
            self._client = nacos.NacosClient(
                server_addresses=os.getenv('NACOS_SERVER_ADDR', 'http://localhost:8848'),
                namespace=os.getenv('NACOS_NAMESPACE', 'public')
            )
    
    def get_config(self, data_id, group='DEFAULT_GROUP'):
        """获取配置"""
        try:
            content = self._client.get_config(data_id, group)
            return json.loads(content) if content else {}
        except Exception as e:
            Logger.error(f"Failed to get config from Nacos: {str(e)}")
            return {}

    def listen_config(self, data_id, group, callback):
        """监听配置变化"""
        def inner_callback(args):
            content = args.get('content')
            if content:
                try:
                    config = json.loads(content)
                    callback(config)
                    Logger.info(f"Config updated: {data_id}")
                except Exception as e:
                    Logger.error(f"Failed to parse config: {str(e)}")

        self._client.add_config_watcher(data_id, group, inner_callback) 